//
//  EJSPayForVipViewController.m
//  EnjoyShoppingStreet
//
//  Created by lifayu on 2017/12/19.
//  Copyright © 2017年 lifayu. All rights reserved.
//

#import "EJSPayForVipViewController.h"
#import "EJSVipInfoRequest.h"
#import "EJSPayForVipRequest.h"

#import "BraintreeCore.h"
#import "BraintreeDropIn.h"
#import "BraintreePayPal.h"
#import <BraintreeCard.h>
#import <BTAPIClient.h>

@interface EJSPayForVipViewController ()<BTViewControllerPresentingDelegate,BTAppSwitchDelegate,BTCardFormViewControllerDelegate,BTDropInControllerDelegate>

@property (weak, nonatomic) IBOutlet UILabel *payPriceLabel;
@property (strong, nonatomic) UIButton *selectedPayMethodButton;
@property (assign, nonatomic) NSInteger payMethod;//0 paypal 1 信用卡

@end

@implementation EJSPayForVipViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.title = @"购买会员卡";
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)configOwnViews{
    self.payPriceLabel.text = [NSString stringWithFormat:@"€ %@",self.vipInfoModel.price];
}

- (IBAction)selectPayMethodAction:(UIButton *)sender {
    if(_selectedPayMethodButton == sender){
        return;
    }
    sender.selected = YES;
    _selectedPayMethodButton.selected = NO;
    _selectedPayMethodButton = sender;
    _payMethod = _selectedPayMethodButton.tag;
}

- (IBAction)payAction:(UIButton *)sender {
    if(_payMethod == -1){
        [[HUDHelper sharedInstance] tipMessage:@"请选择支付方式"];
        return;
    }
    if (_payMethod == 0){
        [self payForPaypal];
    }else if (_payMethod == 1){
        [self payForCard];
    }
}

#pragma mark - 信用卡支付
- (void)payForCard{
    [[HUDHelper sharedInstance] syncLoading];
    BTAPIClient *client = [[BTAPIClient alloc] initWithAuthorization:self.clientToken];
    [client fetchOrReturnRemoteConfiguration:^(BTConfiguration * _Nullable configuration, NSError * _Nullable error) {
        [[HUDHelper sharedInstance] syncStopLoading];
        dispatch_async(dispatch_get_main_queue(), ^{
            if (!error) {
                NSArray *supportedCardTypes = [configuration.json[@"creditCards"][@"supportedCardTypes"] asArray];
                NSMutableArray *paymentOptionTypes = [NSMutableArray new];
                for (NSString *supportedCardType in supportedCardTypes) {
                    BTUIKPaymentOptionType paymentOptionType = [BTUIKViewUtil paymentOptionTypeForPaymentInfoType:supportedCardType];
                    if (paymentOptionType != BTUIKPaymentOptionTypeUnknown) {
                        [paymentOptionTypes addObject: @(paymentOptionType)];
                    }
                }
                
                BTDropInRequest *request = [[BTDropInRequest alloc] init];
                request.amount = self.vipInfoModel.price;
                BTAPIClient *braintreeClient = [[BTAPIClient alloc] initWithAuthorization:self.clientToken];
                BTCardFormViewController *cardVC = [[BTCardFormViewController alloc] initWithAPIClient:braintreeClient request:request];
                cardVC.delegate = self;
                cardVC.supportedCardTypes = paymentOptionTypes;
                UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:cardVC];
                nav.modalPresentationStyle = UIModalPresentationFullScreen;
                [self presentViewController:nav animated:YES completion:nil];
            } else {
                
            }
        });
    }];
}
- (void)cardTokenizationCompleted:(BTPaymentMethodNonce * _Nullable )tokenizedCard error:(NSError * _Nullable )error sender:(BTCardFormViewController *) sender{
    dispatch_async(dispatch_get_main_queue(), ^{
        if (tokenizedCard != nil) {
            [self payForVip:tokenizedCard.nonce];
        } else if (error == nil) {
            [[HUDHelper sharedInstance] tipMessage:@"用户取消"];
        }
        [sender dismissViewControllerAnimated:YES completion:nil];
    });
}
- (void)reloadDropInData{
    
}
#pragma mark - Paypal支付
- (void)payForPaypal {
    [[HUDHelper sharedInstance] syncLoading];
    BTAPIClient *braintreeClient = [[BTAPIClient alloc] initWithAuthorization:self.clientToken];
    BTPayPalDriver *payPalDriver = [[BTPayPalDriver alloc] initWithAPIClient:braintreeClient];
    payPalDriver.viewControllerPresentingDelegate = self;
    payPalDriver.appSwitchDelegate = self; // Optional
    
    // Start the Vault flow, or...
    [payPalDriver authorizeAccountWithCompletion:^(BTPayPalAccountNonce *tokenizedPayPalAccount, NSError *error) {
        [[HUDHelper sharedInstance] syncStopLoading];
        [self payForVip:tokenizedPayPalAccount.nonce];
    }];
    
    BTPayPalRequest *request = [[BTPayPalRequest alloc] initWithAmount:self.vipInfoModel.price];
    [payPalDriver requestOneTimePayment:request
                             completion:^(BTPayPalAccountNonce *tokenizedPayPalAccount, NSError *error) {
                                 [[HUDHelper sharedInstance] syncStopLoading];
                                 [self payForVip:tokenizedPayPalAccount.nonce];
                             }];
}

#pragma mark - BTViewControllerPresentingDelegate
// Required
- (void)paymentDriver:(id)paymentDriver
requestsPresentationOfViewController:(UIViewController *)viewController {
    [self presentViewController:viewController animated:YES completion:nil];
}

// Required
- (void)paymentDriver:(id)paymentDriver
requestsDismissalOfViewController:(UIViewController *)viewController {
    [viewController dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - BTAppSwitchDelegate
// Optional - display and hide loading indicator UI
- (void)appSwitcherWillPerformAppSwitch:(id)appSwitcher {
    [[HUDHelper sharedInstance] syncLoading];
}

- (void)appSwitcherWillProcessPaymentInfo:(id)appSwitcher {
    [[HUDHelper sharedInstance] syncStopLoading];
}

- (void)appSwitcher:(nonnull id)appSwitcher didPerformSwitchToTarget:(BTAppSwitchTarget)target {
    
}

- (void)payForVip:(NSString *)nonce{
    EJSPayForVipRequest *req = [EJSPayForVipRequest new];
    req.nonce = nonce;
    req.levelId = self.vipInfoModel.levelId;
    req.amount = self.vipInfoModel.price;
    req.shareCode = @"";
    [req asyncRequestWithsuccessHandler:^(BaseResponse *response) {
        [[HUDHelper sharedInstance] tipMessage:@"支付成功"];
        [self.navigationController popToRootViewControllerAnimated:YES];
    } failHandler:^(BaseResponse *response) {
        [[HUDHelper sharedInstance] tipMessage:response.message];
    }];
}

@end
